//
//  GameListVC.swift
//  d11
//
//  Created by peale on 2018/10/16.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit

class GameListVC: BXBaseVC,UICollectionViewDelegate,UICollectionViewDataSource,MaintainDelegate{
    let  reuseIdentifierID = "GameListCell" //70x70
    var presentingData: [[String:Any]]? {
        get{
            return GlobalInfo.gameInfoData?[segmentData[presentingSegmentIndex]!] as? [[String : Any]]
        }
    }
    var presentingSegmentIndex: Int = 0
    
    var balanceButton: UIButton?
    
    var maintainAlert: AnnouncementAlertView?
    
    var dataNotLoaded: Bool = true
    let segmentData = [
        0: "game",
        1: "new",
        2: "winner"
    ]
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        if kIsIpad == true {
            layout.itemSize = CGSize(width: kScreenWidth/6, height: 100)
        }else{
            layout.itemSize = CGSize(width: kScreenWidth/3, height: 100)
        }
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .vertical
        //   layout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
        // 设置分区头视图和尾视图宽高
        //    layout.headerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        //    layout.footerReferenceSize = CGSize.init(width: kScreenWidth, height: 80)
        
        let collView = UICollectionView.init(frame: CGRect(x:0, y:60, width:kScreenWidth, height:kScreenHeight-60), collectionViewLayout: layout)
        
        if collView.responds(to:#selector(setter: UIView.layoutMargins)) {
            collView.layoutMargins = .zero;
        }
        collView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth.union(UIView.AutoresizingMask.flexibleHeight)
        collView.register(GameListCell.self, forCellWithReuseIdentifier: "GameListCell")
        //  [_collectionView registerClass:[ExploreHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:cellHeadReuseIdentifierID];
        collView.showsVerticalScrollIndicator = false
        collView.showsHorizontalScrollIndicator = false
        collView.backgroundColor = UIColor.white
        collView.delegate = self
        collView.dataSource = self
        collView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
             self.pullToRefresh()
        })
        return collView
    }()
    
    
    func initSegment(){
        let items = ["热门","新上架","大赢家"] as [Any]
        let segmentedControl = UISegmentedControl(items:items)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.addTarget(self, action: #selector(segmentedControlChanged(_:)), for: UIControl.Event.valueChanged)
        segmentedControl.tintColor = HexRGBAlpha(0x424242,1)
        self.view.addSubview(segmentedControl)
         segmentedControl.snp.makeConstraints{(make) in
            make.width.equalTo(250)
            make.height.equalTo(30)
            make.top.equalTo(15)
            make.centerX.equalToSuperview()
            
        }
    }
    
    @objc func segmentedControlChanged(_ sender: UISegmentedControl) {
        let index = sender.selectedSegmentIndex
        switch index {
        case 0:
            ToolHelper.statisticsPage(pageName: "底部导航-游戏-热门")
            break
        case 1:
            ToolHelper.statisticsPage(pageName: "底部导航-游戏-新上架")
            break
        case 2:
            ToolHelper.statisticsPage(pageName: "底部导航-游戏-大赢家")
            break
        default:
            break
        }
        presentingSegmentIndex = index
        self.collectionView.reloadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        
        self.balanceButton = self.initRightBarBtn()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: balanceButton!)
        
        self.presentingSegmentIndex = 0
        self.initSegment()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.collectionView)
        ToolHelper.statisticsPage(pageName: "底部导航-游戏-热门")
        self.refreshBalance()
    }

    
    func refreshBalance(){
        if UserHelper.getLoginStatus() {
            print("\(String(describing: GlobalInfo.memberInfoData))")
            if let withBalance = GlobalInfo.memberInfoData!["balance"] as? String {
                if withBalance != ""{
                    let balance: Double = Double(withBalance)!
                    self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                }else{
                    self.balanceButton?.setTitle(String(format: "0.00"), for: .normal)
                }
                let size = self.balanceButton!.intrinsicContentSize
                self.balanceButton!.frame.size = CGSize(width: size.width+5, height: 33)
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
            let size = self.balanceButton!.intrinsicContentSize
            self.balanceButton!.frame.size = CGSize(width: size.width+5, height: 33)
        }
    }
    
    @objc func loginRegisterButtonClick(){
        setRootLoginVC()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if GlobalInfo.isMaintain() {
            self.refreshMaintain()
        }else if self.dataNotLoaded {
            self.dataNotLoaded = false
            self.pullToRefresh()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getUserInfo()
        
    }
    
    func refreshMaintain(){
        self.maintainAlert?.dismiss(animated: true)
        self.maintainAlert = nil
        
        self._loadView?.removeFromSuperview()
        self._loadView = UIHelper.initLoadView(self)
        self.tabBarController?.view.addSubview(self._loadView!)
        
        RequestHelper.get(GlobalInfo.resDomain, atPath: "/game_new.json", withCompletion: { data in
            let gameInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            GlobalInfo.gameInfoData = gameInfoArray
            
            DispatchQueue.main.async {
                if GlobalInfo.isMaintain() {
//                    self.alertMaintain()
                    print("alertMaintain")
                }else{
                    self.pullToRefresh()
                }
                self._loadView?.removeFromSuperview()
            }
        }, withError: { error in
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "无法获取配置文件信息，请联系客服,\(getErrorString())", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
                self.collectionView.mj_header?.endRefreshing()
            }
        })
    }
    
    func alertMaintain() {
        self.dataNotLoaded = true
        self.maintainAlert?.dismiss(animated: true)
        self.maintainAlert = UIHelper.initMaintainView(self)
        self.maintainAlert!.show(target: self.tabBarController!, animated: true)
    }
    
    func switchToTabSupport() {
        self.maintainAlert?.dismiss(animated: true)
        self.tabBarController?.selectedIndex = 2
    }
    
    func pullToRefresh(){
        RequestHelper.get(GlobalInfo.resDomain, atPath: "/game_new.json", withCompletion: { data in
            var gameInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            
            /**** Game Info Data ****/
            gameInfoArray.removeValue(forKey: "platforms")
            GlobalInfo.gameInfoData = gameInfoArray
            
            DispatchQueue.main.async {
                self.collectionView.reloadData()
                self.collectionView.mj_header?.endRefreshing()
            }
            
        }, withError: { error in
            DispatchQueue.main.async {
              
                UIHelper.alertSimpleMessage(about: "无法获取配置文件信息，请联系客服,\(getErrorString())", withDescription: "", in: self)
                self.collectionView.mj_header?.endRefreshing()
            }
        })
    }
    
    //获取会员信息
    func getUserInfo() -> Void {
        if UserHelper.getLoginStatus() {
            //api2.0接口开始
            NetWorkRequest(API.memberInfoUL(url: "face82b", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion:  { (responseData,statusCode,strData) -> (Void) in
                if(statusCode == 200){
                    //取出data的数据并转化为字典数据
                    let dataDict = responseData["data"].dictionaryObject
                    //获取到状态值
                    let statusStringJson = responseData["status"]
                    //把状态值的字符串转为int值
                    let statusString = Int("\(statusStringJson)")
                    //获取到传递过来的msg
                    let msgStringJson = responseData["msg"]
                    //把msgStringJson转为字符串
                    let msgString = "\(msgStringJson)"
                    //判断是否相等的
                    if(statusString == 0){
                        let memberInfoArray = dataDict?["response"] as? [String:Any] ?? [:]
                        GlobalInfo.memberInfoData = memberInfoArray
                        print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
                        DispatchQueue.main.async {
                            self.refreshBalance()
                        }
                    }else{
                        DispatchQueue.main.async {
                            //弹出报错后的问题
                            UIHelper.alertSimpleMessage(about: msgString, withDescription: "", in: self)
                        }
                    }
                    
                }else{
                    DispatchQueue.main.async {
                        //弹出报错后的问题
                        UIHelper.alertSimpleMessage(about: "获取用户信息失败!", withDescription: "", in: self)
                    }
                }
            },failed: {(faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    if reCode == "21002"{
                      //  UIHelper.displayLoginExpireTip(self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                    }
                }
                
            }){() -> (Void) in
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "网络请求异常,获取用户信息失败。", withDescription: "", in: self)
                    
                }
            }
            //api2.0接口结束
            
            
//            RequestHelper.get(atPath: "/clientsAPIs/memberInfoUL", withCompletion: { data in
//                let memberInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
//                GlobalInfo.memberInfoData = memberInfoArray
//                print("用户信息: \(memberInfoArray),\(String(describing: GlobalInfo.memberInfoData))")
//                DispatchQueue.main.async {
//                    self.refreshBalance()
//                }
//            }, withError: { error in
//                UIHelper.alertSimpleMessage(about: "服务器异常,\(getErrorString())", withDescription: "", in: self)
//            })
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if GlobalInfo.isMaintain() {
            return 0
        }
        
        if presentingData != nil {
            return presentingData!.count
        }
        return 0
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:GameListCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierID, for: indexPath) as! GameListCell
        cell.setData(dict: presentingData![indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        
        LoginViewController.loginIfNeedController(currentController: self) {
            let game = self.presentingData?[indexPath.row]
            let gpid = game?["gpid"] as! String
            
            if (gpid == "11964220589606") || (gpid == "11964220589608960") {
                if (UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)?.count)! > 9 {
                    UIHelper.alertSimpleMessage(about: "账号长度警告", withDescription: "很抱歉，根据MG手机版本特殊限制，目前只允许账号长度不超过九位的玩家进入，您当前账号长度超出。", in: self)
                    return
                }
                
                self.continueWithGamePlatform(platform: game!)
            }else{
                self.continueWithGamePlatform(platform: game!)
            }
            collectionView.deselectItem(at: indexPath, animated: true)
        }
    }
    
    //转入余额
    func gameAction(_ platform: [String:Any]){
        if UserHelper.getLoginStatus() {
            self._loadView = UIHelper.initLoadView(self, withMessage: "自动转入余额")
            self.parent?.view.addSubview(self._loadView!)
            RequestHelper.post(atPath: "/kz/gp/onekeyri",  withData: ["toid":platform["accid"] as! String], withCompletion: { data in
                let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
                let code = responseObject["c"] as! Int
                
                print(responseObject)
                DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                }
                
                if code == 0 {
                    let responseDetail = responseObject["d"] as! [String:Any]
                    let responseDetailI = responseDetail["i"] as? [String:Any]
                    
                    if responseDetailI == nil {
                        DispatchQueue.main.async {
                           
                            UIHelper.alertSimpleMessage(about: "转入余额参数有误，请联系客服协助处理", withDescription: "", in: self)
                        }
                        return
                    }
                    let c = Int(responseDetailI!["c"] as? Int ?? 0)
                    if c == 0 || c == 1051 {
                        
                        DispatchQueue.main.async {
                            self.checkEnter(platform)
                        }
                    }else if c == 999 || c == 1150 {
                        UIHelper.displayLoginExpireTip(self)
                    }
                }else if code == 999 || code == 1150 {
                    DispatchQueue.main.async {
                        UIHelper.displayLoginExpireTip(self)
                    }
                }else {
                    DispatchQueue.main.async {
                        UIHelper.alertSimpleMessage(about: "发生错误: \(code) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                    }
                }
            }, withError: { error in
                print(error)
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: "一键回收未成功，请稍后重试。\(getErrorString())", withDescription: "", in: self)
                    self._loadView?.removeFromSuperview()
                }
            })
        }else{
            LoginViewController.loginIfNeedController(currentController: self) {}
        }
    }
    
    
    //检查账户
    func checkEnter(_ platform: [String:Any]){
        let gpid = platform["gpid"] as? String  ?? ""
        
        self._loadView?.removeFromSuperview()
        self._loadView = UIHelper.initLoadView(self, withMessage: "检查账户...")
        self.parent?.view.addSubview(self._loadView!)
        RequestHelper.post(atPath: "/kz/gp/v1/enter?id="+gpid, withData: ["accid":gpid], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:]
            let code = responseObject["code"] as? Int ?? 0
            print("!!!\(responseObject)")
            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                if code == 0 {
                    var data = responseObject["data"] as? [[String:Any]]  ?? []
                    if data.count <= 0{
                        UIHelper.alertSimpleMessage(about: "接口数据异常。", withDescription: "", in: self)
                        return
                    }
                    var s = data[0]
                    if s["status"] as? Int ?? -1 == 1 {
                        let gp = data[1]
                        if gp["status"] as? Int ?? -1 == 1 {
                            if gp["c"] as? Int ?? -1 == 1 {
                                //进入游戏
                                let str: Any? = (data[2]["data"] as! [String:Any])["val"]
                                var zeroFlag: Bool = false
                                if str is String {
                                    zeroFlag = ((str as? String) == "0.00")
                                }
                                else {
                                    zeroFlag = (str as? Int) == 0
                                }
                                //判断是否为沙巴，若是沙巴则检查NB是否为0
//                                if (gpid == "8246252097638400") && zeroFlag {
//                                    UIHelper.alertSimpleMessage(about: "沙巴平台余额提醒", withDescription: "沙巴平台余额为0的情况下无法游戏，请先转账", in: self, withOKButton: true)
//                                    return
//                                }
                                
                                self._loadView?.removeFromSuperview()
                                self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏...")
                                self.view.addSubview(self._loadView!)
                                self.pushGameViewController(platform)
                            }else {
                                //注册游戏
                                //                              [UIHelper displayTip:@"系统维护中，当前无法进入游戏" delay:1.5f view:self.view];
                                //checkREG(accid, url: url)
                                print("Need Registeration")
                                self.checkReg(platform)
                            }
                        }
                        else {
                            UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。", withDescription: "", in: self)
                        }
                    }
                    else {
                        let tip: String = "系统维护中(\(s["s"] as? String ?? "")-\(s["e"] as? String ?? ""))，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。"
                        UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                    }
                }
                else if code == 999 || code == 1150 {
                    UIHelper.displayLoginExpireTip(self)
                }
                else {
                    UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
    
     //检查账号
    func checkReg(_ platform: [String:Any]){
        self._loadView?.removeFromSuperview()
        self._loadView = UIHelper.initLoadView(self, withMessage: "检查账号...")
        self.parent?.view.addSubview(self._loadView!)
        
        RequestHelper.post(atPath: "", withData: [:], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            let code = responseObject["c"] as! Int
            
            DispatchQueue.main.async {
                self._loadView?.removeFromSuperview()
                if code == 0 {
                    //进入游戏
                    self.pushGameViewController(platform)
                }
                else if code == 1407 {
                    UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。", withDescription: "", in: self)
                }
                else if code  == 999 || code  == 1150 {
                    UIHelper.displayLoginExpireTip(self.parent!)
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
    
    //进入web游戏页面
    func pushGameViewController(_ gp: [String:Any]){
        self._loadView?.removeFromSuperview()
        let goNext = GameWKWebViewController.instanceFromStoryboard()!
        print("游戏 \(gp["title"] as? String ?? "未知")")
    
        goNext.gpid = gp["gpid"] as? String
        goNext.url = gp["url"] as? String
        //   goNext.isChangeRotate = true
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    
    //2.0进入游戏平台
    func continueWithGamePlatform(platform:[String:Any]?){
           let isMaintain = platform?["status"] as? Int ?? 0
                  
           if UserHelper.getLoginStatus() {
               //mt
               if isMaintain == 0 {
                   UIHelper.alertSimpleMessage(about: "此游戏平台正在维护", withDescription: "", in: self)
                   return
               }
               self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏中...")
               self.parent?.view.addSubview(self._loadView!)
               NetWorkRequest(API.goInGamePlatform(url: "04976c8", gpid: platform!["gpid"] as? String ?? ""), completion: { (responseData,statusCode,strData) -> (Void) in
                    DispatchQueue.main.async {
                       self._loadView?.removeFromSuperview()
                        let dataDict = responseData["data"].dictionary
                        let onekeyriResponse = dataDict?["onekeyriResponse"]?.dictionary
                        let enterGameResponse = dataDict?["enterGameResponse"]?.dictionary
                       let oresponse = onekeyriResponse?["response"]?.dictionary
                       let code = oresponse?["c"]?.int  ?? -1
                       if code == 0 {
                        let ecode =  enterGameResponse?["code"]?.int ?? -1
                           if ecode == 0{
                               let data = enterGameResponse?["data"]?.array
                               if data?.count ?? 0 <= 0 {
                                    UIHelper.alertSimpleMessage(about: "数据异常。", withDescription: "", in: self)
                                   return
                               }
                               //获取数组第一个的数据
                               let s = data?[0].dictionaryObject
                               if s?["status"] as? Int ?? -1 == 1 {
                                   let gp = data?[1].dictionaryObject
                                   if gp?["status"] as? Int ?? -1 == 1 {
                                       if gp?["c"] as? Int ?? -1 == 1  || gp?["c"] as? Int ?? -1 == 0{
                                        let dict = data?[2].dictionaryObject
                                           if let str = (dict?["data"] as? [String:Any])?["val"] {
                                               var zeroFlag: Bool = false
                                               if str is String {
                                                   zeroFlag = ((str as? String) == "0.00")
                                               }else {
                                                   zeroFlag = ((str as? Int) == 0)
                                               }
                                               //判断是否为沙巴，若是沙巴则检查NB是否为0
//                                               if (platform!["gpid"] as? String ?? "" == "8246252097638400") && zeroFlag {
//                                                   UIHelper.alertSimpleMessage(about: "沙巴平台余额提醒", withDescription: "沙巴平台余额为0的情况下无法游戏，请先转账", in: self, withOKButton: true)
//                                                   return
//                                               } else {
                                                   //进入游戏
                                                   self.pushGameViewController(platform!)
//                                               }
                                           }else{
                                               UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。", withDescription: "", in: self)
                                           }
                                       }else{
                                           //注册游戏
                                           print("注册游戏")
                                           UIHelper.alertSimpleMessage(about: "注册游戏失败，请稍后重试。", withDescription: "", in: self)
                                        //    self.checkReg(platform!)
                                       }
                                   }else{
                                       UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐", withDescription: "", in: self)
                                   }
                               }else{
                                   let tip: String = "系统维护中(\(s?["s"] as? String ?? "")-\(s?["e"] as? String ?? ""))，当前无法进入游戏"
                                   UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                               }
                           }else if code == 999 || code == 1150 {
                               LoginViewController.loginIfNeedController(currentController: self) {}
                           }else{
                               UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                           }
                       }else if code == 999 || code == 1150 {
                            LoginViewController.loginIfNeedController(currentController: self) {}
                       }else{
                            UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                       }
                   }
               }, failed: { (faildInfo,reCode,msg) -> (Void) in
                   DispatchQueue.main.async {
                       if reCode == "21002"{
                           LoginViewController.loginIfNeedController(currentController: self) {}
                       }else{
                           UIHelper.alertSimpleMessage(about: "发生错误: \(Int(reCode)) \(CodeMessageHelper.get(String(reCode)))", withDescription: "", in: self)
                       }
       
                       self._loadView?.removeFromSuperview()
                   }
               }) { () -> (Void) in
                   DispatchQueue.main.async {
                           UIHelper.alertSimpleMessage(about: "发生错误，请联系客服协助处理，\(getErrorString())", withDescription: "", in: self)
                           self._loadView?.removeFromSuperview()
                   }
               }
           }else{
               LoginViewController.loginIfNeedController(currentController: self) {}
           }
       }
    
    
}
